package com.rabbitmq.demo.producer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeoutException;

/**
 * 生产者有三种消息确认方式：串行，批量和异步
 * 持久化：如果MQ服务器奔溃，再次启动后，消息依据保持不会丢失
 *      交换器的持久化是通过声明交换器durable参数为true实现的
 *      队列持久化是通过声明队列durable参数为true实现的
 *      消息持久化：BasicProperties的deliveryMode为true
 */
public class RabbitMQConfirmProducer {
    private static String host = "127.0.0.1";
    private static String userName = "guest";
    private static String passWord = "guest";
    private static int port = 5672;
    private static final  String ExchangeName = "topicConfirm";
    private static String routingKey = "com.mq.rabbit.error";
    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            //1、连接到RabbitMQ服务器
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            factory.setPort(port);
            factory.setUsername(userName);
            factory.setPassword(passWord);
            Connection connect = factory.newConnection();
            Channel channel = connect.createChannel();
            //2、声明交换机
            //交换器的持久化是通过声明队列durable参数为true实现的
            channel.exchangeDeclare(ExchangeName, "topic",true); // 声明topic交换器
            //3、发送消息到name为ExchangeName的交换机并设置消息的路由关键字routingKey
            useConfirmMode(channel,3);
            channel.close();
            connect.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void useConfirmMode(Channel channel, int modeType) throws IOException, InterruptedException {
        switch (modeType){
            case 1:
                serialConfirmMode(channel);
                break;
            case 2:
                batchConfirmMode(channel);
                break;
            case 3:
                asyncConfirmMode(channel);
                break;
        }
    }

    /**
     * 串行confirm模式
     * 每发一个消息就等待确认，效率低
     * @param channel
     * @throws InterruptedException
     * @throws IOException
     */
    private static void serialConfirmMode(Channel channel) throws InterruptedException, IOException {
        channel.confirmSelect();
        for(int i = 0; i < 5 ;i++) {
            channel.basicPublish(ExchangeName, routingKey, null, "hello rabbit".getBytes("UTF-8"));
            //方式一:串行confirm
            if(!channel.waitForConfirms()){
                System.out.println(i+": serial send message failed.");
            }else{
                System.out.println(i+": serial send message success.");
            }
        }
    }


    /**
     * 批量confirm模式
     * 批量发送一定消息，然后等待确认，效率较高，但一旦确认失败，所有消息需要重发
     * @param channel
     * @throws InterruptedException
     * @throws IOException
     */
    private static void batchConfirmMode(Channel channel) throws InterruptedException, IOException {
        channel.confirmSelect();
        for(int i = 0; i < 5 ;i++) {
            channel.basicPublish(ExchangeName, routingKey, null, "hello rabbit".getBytes("UTF-8"));
        }
        //方式一:串行confirm
        if(!channel.waitForConfirms()){
            System.out.println("batch send message failed.");
        }else{
            System.out.println("batch send message success.");
        }
    }

    /**
     * 异步确认
     * 无需等待消耗资源，可以提高系统吞吐量
     * @param channel
     * @throws IOException
     */
    private static void asyncConfirmMode(Channel channel) throws IOException, InterruptedException {
        final SortedSet<Long> confirmSet = Collections.synchronizedSortedSet(new TreeSet<Long>());
        channel.confirmSelect();
        channel.addConfirmListener(new ConfirmListener() {
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("Ack, SeqNo: " + deliveryTag + ", multiple: " + multiple);
                if (multiple) {
                    confirmSet.headSet(deliveryTag + 1).clear();
                } else {
                    confirmSet.remove(deliveryTag);
                }
            }
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("Nack, SeqNo: " + deliveryTag + ", multiple: " + multiple);
                if (multiple) {
                    confirmSet.headSet(deliveryTag + 1).clear();
                } else {
                    confirmSet.remove(deliveryTag);
                }
            }
        });

        while (true) {
            long nextSeqNo = channel.getNextPublishSeqNo();
            channel.basicPublish(ExchangeName, routingKey, MessageProperties.PERSISTENT_TEXT_PLAIN, "hello rabbit".getBytes("UTF-8"));
            confirmSet.add(nextSeqNo);
            Thread.sleep(1000);
        }
    }
}
